package com.zm.xdata.service.publics.poster.Interceptor;

import com.zm.xdata.service.publics.poster.model.base.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.security.auth.login.LoginException;

/**
 * @description: 全局统一异常处理
 * @author: YuXD
 * @create: 2019-01-14 15:05
 **/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHanlder {

    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public ApiResult<String> errorHandle(RuntimeException ex) {
        // 打印异常信息到日志
        log.error(ex.getMessage(), ex);

        ApiResult<String> apiResult = new ApiResult();
        return apiResult.dataError(ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ApiResult<String> errorHandle(Exception ex) {
        // 打印异常信息到日志
        log.error(ex.getMessage(), ex);
        ApiResult<String> apiResult = new ApiResult();
        return apiResult.fail(ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = NullPointerException.class)
    public ApiResult<String> errorHandle(NullPointerException ex) {
        // 打印异常信息到日志
        log.error(ex.getMessage(), ex);
        ApiResult<String> apiResult = new ApiResult();
        return apiResult.fail(ex.getMessage());
    }

    /**
     * 用户登录异常
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = LoginException.class)
    public ApiResult errorHandle(LoginException ex) {
        ApiResult apiResult = new ApiResult();
        return apiResult.fail(ex.getMessage());
    }

}
